﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MipsMachine
{
	public enum OutputFormat
	{
		Binary,
		PE,
		ELF
	}
	public class MipsProgram
	{
		internal List<MipsInstruction> instructions;
        private int entry_point;

		public List<MipsInstruction> Program { get { return instructions; } }

        public int EntryPoint { get { return entry_point; } set { entry_point = value; } }

		public MipsProgram()
		{
			instructions = new List<MipsInstruction>();
		}

		public static MipsProgram FromBin(System.IO.Stream src)
		{
			MipsProgram ret = new MipsProgram();
			var buf = new byte[4];
			
			while (src.Position < src.Length)
			{
				src.Read(buf, 0, 4);
				uint val = BitConverter.ToUInt32(buf, 0);
				//SwapEndian(ref val);
				ret.instructions.Add(new MipsInstruction(val));
			}
			return ret;
		}
		public static MipsProgram FromBin(string filename)
		{
			using (var fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
			{
				return FromBin(fs);
			}
		}
		private static void SwapEndian(ref uint val)
		{
			val = (val >> 24) |
					((val << 8) & 0x00FF0000) |
					((val >> 8) & 0x0000FF00) |
					(val << 24);

		}

		public void Save(System.IO.Stream dst)
		{

		}
		public void SavePe(System.IO.Stream dst)
		{
		}
        public void SaveBin(string filename)
        {
            using (var fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                SaveBin(fs);
            }
        }

		public string GenerateCil()
		{
			return "Not implemented.";
		}

		public void SaveBin(System.IO.Stream dst)
		{
			foreach (var ins in instructions)
			{
				uint val = (uint)ins;
				//SwapEndian(ref val);
				var bytes = BitConverter.GetBytes(val);
				dst.Write(bytes, 0, bytes.Length);
			}
		}
		public void SaveElf(System.IO.Stream dst)
		{
		}
	}
}
